var FormComponents = function () {

    var handleSelect2Modal = function () {

        (function ($) {
            $.extend({
                Request: function (m) {
                    var sValue = location.search.match(new RegExp("[\?\&]" + m + "=([^\&]*)(\&?)", "i"));
                    return sValue ? sValue[1] : sValue;
                },
                UrlUpdateParams: function (url, name, value) {
                    var r = url;
                    if (r != null && r != 'undefined' && r != "") {
                        value = encodeURIComponent(value);
                        var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
                        var tmp = name + "=" + value;
                        if (url.match(reg) != null) {
                            r = url.replace(eval(reg), tmp);
                        }
                        else {
                            if (url.match("[\?]")) {
                                r = url + "&" + tmp;
                            } else {
                                r = url + "?" + tmp;
                            }
                        }
                    }
                    return r;
                }
            });
        })(jQuery);

        $("#e1").select2({
            minimumInputLength: 2,
            query: function (query) {
                $.get(baseUrl + "index.php/brandManage/search", {name:query.term}, // 提交的页面
                function(data) {
                    query.callback(data);
                });
            }
        });

        $("#delShopImage").click(function(){
            $('input[name=shopimage]').val("");
            $('input[name=shopimage]').prev().attr("src","assets/fileUpload.jpg");
        });

        $("#e2").select2({
            minimumInputLength: 1,
            query: function (query) {
                $.get(baseUrl + "index.php/categoryManage/search", {name:query.term}, // 提交的页面
                function(data) {
                    query.callback(data);
                });
            }
        }); 
        
        $("form").validation();
        $('#addForm').submit(function(){
            if ($("form").valid()==false)
                return false;
            if($('.image_tiles').children().length==0)
            {
                alert("商品图片不能为空");
                return false;
            }
                 $.ajax({
                    url: baseUrl+"index.php/goodsManage/add",   // 提交的页面
                    data: $('#addForm').serialize(), // 从表单中获取数据
                    type: "POST",                   // 设置请求类型为"POST"，默认为"GET"
                    error: function(request) {      // 设置表单提交出错
                        alert("表单提交出错，请稍候再试");
                        return false;
                    },
                    success: function(data) {

                            window.location.href = "goods.html";
                        }
                    });
                return false;
            });


        

    }

    return {
        //main function to initiate the module
        init: function () {
            handleSelect2Modal();

            $('.fileUpload').each(function(){
                
                $(this).click(function(){
                    $(this).prev().click();
                });

                var fileName = $(this).next();
                $(this).prev().fileupload({
                        url: baseUrl+"index.php/site/upload",
                        dataType: 'json',
                        autoUpload: true,

                        done: function (e, data) {
                            $.each(data.result.files, function (index, file) {
                                //$('<p/>').text(file.name).appendTo('#files');
                                fileName.val(file.url);
                                fileName.prev().attr("src",baseUrl+file.url);
                            });
                        },
                });

            });

            $('#addImage').fileupload({
                        url: baseUrl+"index.php/site/upload",
                        dataType: 'json',
                        autoUpload: true,

                        done: function (e, data) {
                            $.each(data.result.files, function (index, file) {
                                //$('<p/>').text(file.name).appendTo('#files');
                                $(".image_tiles").append('<div class="tile blue"><img src="'+baseUrl+file.url+'" class="img-thumbnail fileUpload" alt=""><input type="hidden" name="images[]" value="'+file.url+'"></div>');
                            });
                        },
                });

            $(".image_tiles").on("click",".tile",function(){
                $(this).remove();
            });

            $.get(baseUrl + "index.php/tagManage/getList", {}, // 提交的页面
                function(data) {
                    for(var key in data){
                        $(".tag_tiles").append("<div class='tile bg-purple' data-en='"+data[key]['name_en']+"' data-zn="+data[key]['name_zn']+"><div class='tile-body'><p>"+data[key]["name_zn"]+"</p><p>"+data[key]["name_en"]+"</p> </div></div>");
                    }

                    if($.Request('id') !=null )
                    {
                        $.get(baseUrl+"index.php/goodsManage/getById",{id:$.Request('id')},   // 提交的页面
                                function(data) {
                                    $('input[name=id]').val(data._id);
                                    $('input[name=brand]').val(data.brand);
                                    $('input[name=brand]').prev().find('.select2-chosen').text(data.brandname);
                                    $('input[name=category]').val(data.category);
                                    $('input[name=category]').prev().find('.select2-chosen').text(data.categoryname);
                                    $('input[name=name_zn]').val(data.name_zn);
                                    $('input[name=name_en]').val(data.name_en);
                                    $('input[name=hours]').val(data.hours);
                                    $('textarea[name=desc_en]').val(data.desc_en);
                                    $('textarea[name=desc_zn]').val(data.desc_zn);
                                    $('input[name=code]').val(data.code);
                                    $('input[name=icon]').val(data.icon);
                                    if(data.icon!="")$('input[name=icon]').prev().attr("src",baseUrl+data.icon);
                                    $('input[name=freight]').val(data.freight);
                                    $('input[name=size]').val(data.size);
                                    $('input[name=icon]').val(data.icon);
                                    $('input[name=shopimage]').val(data.shopimage);
                                    if(data.shopimage!="")$('input[name=shopimage]').prev().attr("src",baseUrl+data.shopimage);
                                    $('input[name=shopaddress]').val(data.shopaddress);
                                    $('input[name=originPrice]').val(data.originPrice);
                                    $('input[name=inventory]').val(data.inventory);
                                    $('input[name=placeOfOrigin_zn]').val(data.placeOfOrigin_zn);
                                    $('input[name=placeOfOrigin_en]').val(data.placeOfOrigin_en);
                                    $('textarea[name=technology_zn]').val(data.technology_zn);
                                    $('textarea[name=technology_en]').val(data.technology_en);
                                    $('textarea[name=material_zn]').val(data.material_zn);
                                    $('textarea[name=material_en]').val(data.material_en);

                                    $('#categoryTag').val(data.categoryTag);
                                    $('#categoryTag').prev().find('.select2-chosen').text(data.categoryTag);

                                    for(var key in data.images)
                                        $(".image_tiles").append('<div class="tile blue"><img src="'+baseUrl+data.images[key]+'" class="img-thumbnail fileUpload" alt=""><input type="hidden" name="images[]" value="'+data.images[key]+'"></div>');
                                    for(var key in data.tags_zn)
                                    {


                                        $(".tag_tiles").find('[data-zn='+data.tags_zn[key]+']').removeClass('bg-purple').addClass('bg-green')
                                        .append("<input type='hidden' name='tags_en[]' value='"+data.tags_en[key]+"'>").append("<input type='hidden' name='tags_zn[]' value='"+data.tags_zn[key]+"'>");
                                    }
                                }
                            );
                    }
                }
            );

            $(".tag_tiles").on("click",".tile",function(){
                if($(this).hasClass('bg-purple')){
                    $(this).removeClass('bg-purple');
                    $(this).addClass('bg-green');
                    $(this).append("<input type='hidden' name='tags_en[]' value='"+$(this).attr('data-en')+"'>")
                    $(this).append("<input type='hidden' name='tags_zn[]' value='"+$(this).attr('data-zn')+"'>")
                }else{
                    $(this).removeClass('bg-green');
                    $(this).addClass('bg-purple');
                    $(this).find('input').remove();
                    console.log($(this).find('input'))
                }
            });

        }
    };

}();